<template>
  <div>
    <div id="container"></div>
  </div>
</template>
<script>
import G6 from "@antv/g6";
export default {
  props: {
    g6data: {
      type: Object,
    },
    operate: {
      type: String,
    },
    foldData: {
      type: Object,
    },
  },
  watch: {
    // 因为我这要根据数据切换流程图渲染，所以使用watch监听设置的变量，做不同的渲染。
    operate: {
      deep: true,
      handler() {
        if (this.operate === "fold") {
          // 清空
          this.graph.clear();
          // 重渲folddata
          this.init(this.foldData);
        } else if (this.operate === "extend") {
          // 清空
          this.graph.clear();
          // 重渲g6datas
          this.init(this.g6datas);
        }
      },
    },
  },
  data() {
    return {
      graph: null,
      g6datas: JSON.parse(JSON.stringify(this.g6data)),
    };
  },
  mounted() {
    // 默认渲染g6datas
    this.init(this.g6datas);
  },
  methods: {
    // changeData(data) {
    //   this.graph.changeData(data)
    // },
    init(value) {
      const data = value;
      // 字数超出换行
        data.nodes.forEach((e) => {
          if (e.label.length > 8) {
            e.label = e.label.replace(/(.{8})/g, "$1\n");
          }
        });
      const width = document.getElementById("container").scrollWidth;
      const height = document.getElementById("container").scrollHeight || 600;
      this.graph = new G6.Graph({
        id: "container",
        container: "container",
        width,
        height,
        fitView: false, // 适配，我这里设置为false之后惊喜发现不会因为数据少而一个个特别大
        modes: {
          default: ["drag-canvas", "drag-node"],
        },
        layout: {
          type: "dagre",
          rankdir: "TB",
          align: "", // 方向，设置为空，就实现了一对多时居中
          nodesepFunc: () => 1,
          ranksepFunc: () => 1,
        },
        defaultNode: {
          type: "rect",
          style: {
            lineWidth: 1,
            stroke: "#5B8FF9",
            fill: "#fff",
            redius: 5,
          },
        },
        groupByTypes: false,
        defaultCombo: {
          labelCfg: {
            position: "bottom",
            refY: 5,
            style: {
              fill: "#fff",
              fontSize: 40,
            },
          },
        },
        defaultEdge: {
          size: 1,
          color: "#cccccc",
          style: {
            endArrow: {
              path: G6.Arrow.triangle(10, 12, 35), // 使用内置箭头路径函数，参数为箭头的 宽度、长度、偏移量（默认为 0，与 d 对应）
              d: 30,
              fill: "#cccccc",
              stroke: "#cccccc",
              opacity: 0.4,
              lineWidth: 1,
            },
          },
        },
      });
      this.graph.data(data);
      this.graph.render();
      this.graph.on('node:mouseenter',(ev) =>{
        console.log(ev);
        console.log(ev.item);
      })
    },
  },
};
</script>
<style scoped></style>
